import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

class BusinessCustomerDetailsEditLabelTabForm extends StatefulWidget {
  BusinessCustomerDetailsEditLabelTabForm({Key key, this.response, this.dataSource, this.formDataSource, this.showTitle = true, this.isScroll = false}) : super(key: key);

  final BaseHttpResponseModel response;

  final List<dynamic> dataSource;

  final Map<String, dynamic> formDataSource;

  final bool showTitle;

  final bool isScroll;

  @override
  _BusinessCustomerDetailsEditLabelTabFormState createState() => _BusinessCustomerDetailsEditLabelTabFormState();
}

class _BusinessCustomerDetailsEditLabelTabFormState extends State<BusinessCustomerDetailsEditLabelTabForm> {
  BaseRequestFormProvider baseRequestFormProvider;

  @override
  void initState() {
    List<BaseHttpRequestModel> _requests = this._initContentRequestFields();
    baseRequestFormProvider = BaseRequestFormProvider(requests: _requests, dataSource: widget.formDataSource);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return widget.isScroll ? SingleChildScrollView(child: _buildColumn()) : _buildColumn();
  }

  Widget _buildColumn() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.showTitle) Padding(padding: const EdgeInsets.only(top: 12.0, left: 16.0, right: 12.0, bottom: 0), child: Text(widget.response.name)),
        _buildCardWidget(),
      ],
    );
  }

  Widget _buildCardWidget() {
    return BaseCardComponent(
      padding: EdgeInsets.only(left: 12.0, right: 12.0, top: widget.dataSource.length == 1 ? 0 : 12.0, bottom: widget.dataSource.length == 1 ? 0 : 12.0),
      child: _buildBaseCardContentComponent(),
    );
  }

  Widget _buildBaseCardContentComponent() {
    return baseRequestFormProvider.requests.length == 0 ? BaseEmptyComponent() : BaseRequestForm(baseRequestFormProvider: baseRequestFormProvider, requestSaveData: _saveFormData, isSaveASingle: true);
  }

  void _saveFormData(BaseHttpRequestModel request, Map<String, dynamic> data, {bool notShowLoading}) async {
    String service = '/vipbills/vipuserbills/vipclerk/update/tag';
    String vipId = BaseUtils.getKeyData(widget.formDataSource, 'vipId').toString();
    List<dynamic> tagValues = [];
    var _tagValues = baseRequestFormProvider.getDataKey(request);

    ///单行文本/跳转多行文本(文本域)/日期
    bool inputTypeState = (request.inputType == BaseHttpInputTypeEnum.InputText) || (request.inputType == BaseHttpInputTypeEnum.LinkInputTextArea) || (request.inputType == BaseHttpInputTypeEnum.InputDate) || (request.inputType == BaseHttpInputTypeEnum.InputNumber);
    if (inputTypeState) {
      if (request.inputType == BaseHttpInputTypeEnum.InputDate) {
        tagValues.add({'tagId': BaseTransformUtil.stringToDate(data[request.fieldName])});
      } else {
        tagValues.add({'tagId': data[request.fieldName]});
      }
    }

    ///单选弹窗
    if (request.inputType == BaseHttpInputTypeEnum.SelectDialog) {
      tagValues = [
        {'tagId': _tagValues}
      ];
    }

    ///多选弹窗
    if (request.inputType == BaseHttpInputTypeEnum.MultipleSelectDialog && _tagValues is List) {
      tagValues = _tagValues.map((e) {
        String id = BaseUtils.getKeyData(e, 'key');
        return {'tagId': id};
      }).toList();
    }
    Map<String, dynamic> params = {
      'vipId': vipId,
      'vipTags': [
        {'tagTypeId': request.fieldName, 'tagValues': tagValues}
      ]
    };
    if (notShowLoading == null || !notShowLoading) BaseComponentUtils.showLoadingDialog(context, hint: '正在保存会员信息');
    await dioUtil.fetch(service, params: params);
    if (notShowLoading == null || !notShowLoading) BaseComponentUtils.hideLoadingDialog(context);
  }

  /// 构建入参
  List<BaseHttpRequestModel> _initContentRequestFields() {
    List<dynamic> items = widget.dataSource ?? [];
    List<dynamic> newItems = [...items];
    // 排序 sort
    newItems.sort((before, after) {
      int _beforeSort = BaseDefaultsValue.intDefaults(BaseUtils.getKeyData(before, 'showOrder'), defaultValue: 0);
      int _afterSort = BaseDefaultsValue.intDefaults(BaseUtils.getKeyData(after, 'showOrder'), defaultValue: 0);
      return _beforeSort.compareTo(_afterSort);
    });
    // 排序
    List<BaseHttpRequestModel> requests = [];
    newItems.forEach((element) {
      String accessMode = BaseUtils.getKeyData(element, 'accessMode').toString();
      String fieldName = BaseUtils.getKeyData(element, 'propertyId').toString();
      String name = BaseUtils.getKeyData(element, 'propertyName').toString();
      String notes = BaseUtils.getKeyData(element, 'propertyTag').toString();
      String inputApi = BaseUtils.getKeyData(element, 'inputApi').toString();
      String inputType = BaseUtils.getKeyData(element, 'inputType').toString();
      if (inputType == "InputTextArea") inputType = "LinkInputTextArea";
      String defaultValue = BaseUtils.getKeyData(element, 'inputDefault').toString();
      String propertyRequired = BaseUtils.getKeyData(element, 'propertyRequired').toString();
      BaseHttpRequestModel request = new BaseHttpRequestModel.fromJson({'fieldName': fieldName, 'name': name, 'notes': notes, 'inputApi': inputApi, 'inputType': inputType, 'accessMode': accessMode, 'required': propertyRequired == 'true', 'defaultValue': defaultValue});
      requests.add(request);
    });
    return requests;
  }
}
